import React, { Component } from 'react';
import {
  Row, Col, message, List, Tooltip, Icon, TreeSelect,
} from 'antd';
import { connect } from 'dva';
import { isEmpty, isFunction, findIndex, forEach, map, isObject, isArray, isString } from 'lodash';
import styles from './index.less';
import UploadDragger from '/common/components/UploadDragger';
import classNames from 'classnames';
import apiConfig from '@/apiConfig';
import request from '@/helpers/request';
import { recurAddKeyAndFileds } from '/common/utils/ArrayUtils';
import PhotoSwiper from '/common/components/PhotoSwiper';
import { byte2KOM } from '/common/utils/numberUtils';
import ModalComp from '/common/components/ModalItem/ModalComp';

@connect(({ global: { docList } }) => ({
  dirTreeComp: docList,
}))
class FileUploadDetail extends Component {
  constructor(props) {
    super(props);
    this.itemRef = React.createRef();
    this.state = {
      visible: false,
      mode: 'top',
      previewFile: null,
      dirId: 0,
      isShowPS: false, // 是否显示图片预览浮层
      curFile: {}, // 当前预览的文件
      compUpdateTime: Math.floor(Math.random() * 10000),
    };
    this.uploadTemp = [];
    this.usFile = [];  //上传成功的文件
  }

  componentDidMount() {
    this.props.onRef && (this.props.onRef(this));
    if (this.props.dirTreeComp && isEmpty(this.props.dirTreeComp)) {
      this.fetchList();
    }
    if (!isEmpty(this.props.selectedDirKeys) && this.props.selectedDirKeys) {
      this.setState({
        dirId: this.props.selectedDirKeys[0],
      });
    }
  }

  // componentWillMount(){
  //   console.log('this.props.selectedDirKeys:',this.props.selectedDirKeys);
  //   if(!isEmpty(this.props.selectedDirKeys)&&this.props.selectedDirKeys){
  //     this.setState({
  //       dirId:this.props.selectedDirKeys[0]
  //     });
  //   }
  // }

  /**
   * 获取文件信息
   * @param payload
   */
  fetchList(payload = {}) {
    const { dispatch, compData } = this.props;
    if (!compData) {
      dispatch({
        type: 'global/findDocList',
        payload: payload,
      });
    }
  }

  /**
   * 选择本地图片之后的回调
   * @param fileObj Object 图片对象，包含两个字段：{thumbUrl:"String 图片的 base64 数据，只有图片类型有这个字段", originFileObj:'File 本地文件资源'}
   */
  onBeforeUploadCb(fileObj) {
    const { uploadFileRowCb } = this.props;

    if (fileObj && fileObj.originFileObj) {
      this.uploadTemp.push(fileObj);
      // let tempList = [...uploadTemp, fileObj];
      this.setState({
        compUpdateTime: Math.floor(Math.random() * 10000),
      }, () => {
        uploadFileRowCb &&
        uploadFileRowCb(this.uploadTemp);
      });
    }
  }

  getFileUploadTemp() {
    return this.uploadTemp;
  };

  //删除临时附件信息
  onDeleteUploadTemp(uid) {
    const { uploadFileRowCb } = this.props;
    // if (findIndex(this.uploadTemp, (o) => {
    //   return o.uid == uid;
    // }) != -1) {
    //   this.closePreviewCb();//清除预览效果
    // }
    this.uploadTemp = this.uploadTemp.filter(item => item.uid !== uid);

    this.setState({
      compUpdateTime: Math.floor(Math.random() * 10000),
    }, () => {
      uploadFileRowCb &&
      uploadFileRowCb(this.uploadTemp);
    });
  }

  onClickFile(item, e) {
    e.stopPropagation();
    if (item.thumbUrl) {
      this.setState({ isShowPS: true, curFile: item });
    }
  }

  dealImgs() {

    if (isEmpty(this.uploadTemp)) return [];

    return this.uploadTemp.filter(v => (v && v.thumbUrl && v.originFileObj))
      .map(this._dealFile2Photo);
  }

  _dealFile2Photo(v) {
    if (isEmpty(v)) return {};

    return ({
      uid: v.uid,
      name: v.originFileObj.name,
      src: v.thumbUrl,
    });
  }

  /**
   * 选中目录
   * @param dir
   */
  onChange = (dir) => {
    this.setState({
      dirId: dir,
    });
    this.props.setCurrentDirId &&
    this.props.setCurrentDirId(dir, 'upload');
  };

  selectTree(list) {
    // console.log('list：',list);
    const loop = data => data.map((item) => {
      if (item.children && item.children.length) {
        return <TreeSelect.TreeNode key={item.key}
                                    value={item.id}
                                    title={item.name}>{loop(item.children)}</TreeSelect.TreeNode>;
      }
      return <TreeSelect.TreeNode key={item.key}
                                  value={item.id}
                                  title={item.name}/>;
    });

    return (
      <TreeSelect
        style={{ width: '100%' }}
        placeholder="请选择目录"
        treeDefaultExpandAll
        onChange={this.onChange}
        defaultValue={this.props.selectedDirKeys}
      >
        {loop(list)}
      </TreeSelect>
    );
  }

  //文件路径下拉框\tab1
  filePathSelectView = () => {
    const { dirTreeComp } = this.props;
    let tree = recurAddKeyAndFileds(dirTreeComp);
    // let tree  = dirTreeComp;// recurAddKeyAndFileds();
    //console.log('tree:',tree);
    return (
      <Row>
        <Col span={4} style={{ height: '32px', lineHeight: '32px' }}> <label>文件路径:</label></Col>
        <Col span={20} style={{ paddingRight: 10 }}>
          {this.selectTree(tree)}
        </Col>
      </Row>
    );
  };

  //文件上传
  handleUpload = () => {
    // const { dispatch } = this.props;
    const { dirId } = this.state;
    const uploadTemp = this.uploadTemp;

    if (1 > dirId) {
      message.info('请选择目录');
      return false;
    }

    if (isEmpty(uploadTemp)) {
      message.info('请上传文件');
      return false;
    }

    //上传的文件
    uploadTemp.forEach((file) => {
      if (typeof file.upload_status == 'undefined' || (file.upload_status && file.upload_status !== 1)) {
        let formData = new FormData();
        formData.append('file', file.originFileObj);
        this.upload(formData, dirId, file);
      }
    });
  };

  upload = (formData, dirId, fileInfo) => {
    const { dispatch } = this.props;
    let $this = this;
    request(apiConfig.uploadDocApi, {
      method: 'POST',
      data: formData,
      contentType: 'multipart/form-data',
      params: {
        dirId: dirId,
      },
    }).then(rsp => {
      let status = 0; //未上传
      if (isObject(rsp) && (200 == rsp.status || 1 == rsp.status)) {
        dispatch({
          type: 'global/findDocList',
          payload: {},
        });
        status = 1; //上传成功
        let fileInd = findIndex($this.uploadTemp, (obj) => {
          return obj.uid === fileInfo.uid;
        });
        if (fileInd !== -1) {
          if (isObject(rsp.data)) {
            $this.uploadTemp[fileInd] = { ...$this.uploadTemp[fileInd], ...rsp.data };

          } else if (isString(rsp.data)) {
            const strArr = `${rsp.data}`.split('/');
            $this.uploadTemp[fileInd]['name'] = fileInfo.originFileObj.name;
            $this.uploadTemp[fileInd]['savePath'] = rsp.data;
            $this.uploadTemp[fileInd]['saveName'] = strArr[strArr.length - 1];
            $this.uploadTemp[fileInd]['size'] = fileInfo.originFileObj.size;
            $this.uploadTemp[fileInd]['ext'] = `${strArr[strArr.length - 1]}`.substr(`${strArr[strArr.length - 1]}`.lastIndexOf('.'));
          }
          $this.usFile.push($this.uploadTemp[fileInd]);
        }
      } else {
        status = 2;//上传失败
      }
      this.setUploadFileState(fileInfo, status);
    });
  };

  setUploadFileState(info, status) {
    const uploadTemp = this.uploadTemp, { dirId } = this.state;
    if (!isEmpty(uploadTemp) && isArray(uploadTemp)) {
      let fileInd = findIndex(uploadTemp, (obj) => {
        return obj.uid === info.uid;
      });
      if (fileInd != -1) {
        uploadTemp[fileInd]['upload_status'] = status;
        //检测是否有重复文件
        let tempInd = findIndex(this.usFile, (obj) => {
          return obj.uid == uploadTemp[fileInd]['uid'];
        });
        if (tempInd < 0) {
          this.usFile.push(uploadTemp[fileInd]);
        }
        this.setState({
          compUpdateTime: Math.floor(Math.random() * 10000),
        });
      }

      //检测所有文件是否已上传？
      let isSuccessful = true;
      map(uploadTemp, (obj) => {
        if (typeof obj.upload_status == 'undefined' || obj.upload_status != 1) {
          isSuccessful = false;
          return false;
        }
      });
      if (isSuccessful === true) {
        message.success('上传完成');
        this.props.handleUpload && this.props.handleUpload({ dirId: dirId, files: this.usFile });
        this.props.isModal == true && (this.props.hideModal && isFunction(this.props.hideModal) && this.props.hideModal());
      }
    }
  }

  async handleOk() {
    this.handleUpload();
  };

  handleCancel(e) {
    this.props.hideModal();
  }

  render() {
    const { previewFile, compUpdateTime, curFile } = this.state,
      { isModal, boxHeight } = this.props;
    let isDisabled = true;
    const uploadTemp = this.uploadTemp;
    if (!isEmpty(uploadTemp)) {
      map(uploadTemp, (item) => {
        if (item.upload_status && 2 == item.upload_status) {
          isDisabled = false;
          return false;
        } else if (typeof item.upload_status == 'undefined') {
          isDisabled = false;
          return false;
        }
      });
    }
    const photoList = this.dealImgs();
    const curPhotoInd = curFile && curFile.uid ? findIndex(photoList, (v, k) => (v && v.uid === curFile.uid)) : 0;
    let height = boxHeight ? boxHeight : document.body.offsetHeight - 300;
    const layouts = (
      <Row type={'flex'}>
        <Col span={12}>
          <Row>
            <Col span={24}>{this.filePathSelectView()}</Col>
            <Col span={24} style={{ marginTop: 10, paddingRight: 10, height: height - 42 }}>
              <UploadDragger isPreviewMode={previewFile != null && '' != previewFile}
                             key={compUpdateTime}
                             previewFile={previewFile}
                             onBeforeUploadCb={this.onBeforeUploadCb.bind(this)}
                // closePreviewCb={this.closePreviewCb.bind(this)}
                // changeUploadCb={this.changeUploadCb.bind(this)}
              />
            </Col>
          </Row>
        </Col>
        <Col span={12} className={styles.fileList} style={{ height: height }}>
          <List dataSource={uploadTemp}
                renderItem={item => (
                  <div className={styles.fileContainer}>
                    <div className={styles.filePic}
                         onClick={this.onClickFile.bind(this, item)}
                    >
                      {
                        item.thumbUrl ? (
                          <img src={item.thumbUrl} alt={'图片'}/>
                        ) : <Icon type="file"/>
                      }

                    </div>
                    <div className={styles.fileDetails}
                         onClick={this.onClickFile.bind(this, item)}>
                      <div className={styles.fileName} title={item.originFileObj.name}>
                        {item.originFileObj.name}
                      </div>
                      <div className={styles.filePath}>{byte2KOM(item.originFileObj.size)}</div>
                    </div>
                    {
                      (item.upload_status && 1 === item.upload_status) &&
                      <span className={classNames(styles.uploadStatus, styles.succeed)}>
                                  <Icon type="check-circle"/> 已上传
                              </span>
                    }
                    {
                      (item.upload_status && 2 === item.upload_status) &&
                      <span className={classNames(styles.uploadStatus, styles.error)}>
                                  <Icon type="close-circle"/> 上传失败
                              </span>
                    }
                    <a className={styles.fileDelete}
                       href="javascript:;"
                       onClick={e => {
                         e.stopPropagation();
                         this.onDeleteUploadTemp(item.uid);
                       }}><Icon type="delete"/></a>
                  </div>
                )}/>
          <PhotoSwiper
            visible={this.state.isShowPS}
            onClose={() => {
              this.setState({ isShowPS: false });
            }}
            curInd={curPhotoInd}
            photoList={photoList}
          />
        </Col>
      </Row>
    );
    return (
      isModal === true ?
        <ModalComp
          destroyOnClose={true}
          title={`上传文件`}
          width={document.body.offsetWidth > 1200 ? document.body.offsetWidth * 0.5 : '70%'}
          visible={this.props.isShowDetail}
          onOk={this.handleOk.bind(this)}
          okButtonProps={{
            disabled: isDisabled,
          }}
          onCancel={this.handleCancel.bind(this)}
        >
          {layouts}
        </ModalComp> : layouts
    );
  }
}

FileUploadDetail.defaultProps = {
  boxHeight: 0,
  isModal: true,
  uploadFileRowCb: (rowFile) => {

  },
  hideModal: () => {

  },
  selectedDirKeys: [],
};
export default FileUploadDetail;




